package cn.chiship.framework.third.biz.all.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.common.pojo.vo.ThirdApplicationKeyConfigVo;
import cn.chiship.framework.common.util.FrameworkUtil2;
import cn.chiship.framework.third.core.common.ApplicationTypeEnum;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseCacheConstants;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.all.mapper.ThirdApplicationKeyConfigMapper;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfigExample;
import cn.chiship.framework.third.biz.all.service.ThirdApplicationKeyConfigService;
import cn.chiship.sdk.pay.core.config.AliPayConfig;
import cn.chiship.sdk.pay.core.config.WxPayV3Config;
import cn.chiship.sdk.pay.core.enums.TradeTypeEnum;
import cn.chiship.sdk.third.properties.ChishipWxPubProperties;
import cn.chiship.sdk.third.properties.ChishipZfbMpProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 三方应用集成配置业务接口实现层 2022/6/12
 *
 * @author lijian
 */
@Service
public class ThirdApplicationKeyConfigServiceImpl
        extends BaseServiceImpl<ThirdApplicationKeyConfig, ThirdApplicationKeyConfigExample>
        implements ThirdApplicationKeyConfigService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdApplicationKeyConfigServiceImpl.class);

    @Resource
    ThirdApplicationKeyConfigMapper thirdApplicationKeyConfigMapper;

    @Resource
    private ChishipWxPubProperties chishipWxPubProperties;

    @Value("${chiship.pay.domain.notify}")
    private String notifyDomain;

    @Value("${chiship.pay.wx.app-id2}")
    private String wxAppId2;

    @Value("${chiship.pay.wx.app-id3}")
    private String wxAppId3;

    @Resource
    ChishipZfbMpProperties chishipZfbMpProperties;

    @Autowired
    RedisService redisService;


    @Override
    public void cache() {
        String key = CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_THIRD_CONFIG_PREFIX);
        redisService.del(key);
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria()
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId());
        List<ThirdApplicationKeyConfig> applicationKeyConfigs = thirdApplicationKeyConfigMapper.selectByExample(applicationKeyConfigExample);

        for (ThirdApplicationKeyConfig config : applicationKeyConfigs) {
            ThirdApplicationKeyConfigVo configVo = new ThirdApplicationKeyConfigVo();
            BeanUtils.copyProperties(config, configVo);
            redisService.hset(key, FrameworkUtil2.getChishipDefaultProperties().getId() + "-" + config.getAppId(), configVo);
        }
    }

    @Override
    public BaseResult getByAppId(String appId) {
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria()
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId()).andAppIdEqualTo(appId);
        List<ThirdApplicationKeyConfig> applicationKeyConfigs = thirdApplicationKeyConfigMapper
                .selectByExample(applicationKeyConfigExample);
        if (applicationKeyConfigs.isEmpty()) {
            return BaseResult.ok();
        }
        ThirdApplicationKeyConfig applicationKeyConfig = applicationKeyConfigs.get(0);
        JSONObject json = JSON.parseObject(JSON.toJSONString(applicationKeyConfig));
        if (ApplicationTypeEnum.APPLICATION_TYPE_WX_PUB.getType().equals(applicationKeyConfig.getType())) {
            json.put("serverUrl", chishipWxPubProperties.getServerDomain() + "/check");
            json.put("authorizeUrl", chishipWxPubProperties.getServerDomain() + "/authorize");
            json.put("redirectUrl", chishipWxPubProperties.getServerDomain() + "/redirectUri");
        }
        return BaseResult.ok(json);
    }

    @Override
    public BaseResult insertSelective(ThirdApplicationKeyConfig thirdApplicationKeyConfig) {
        thirdApplicationKeyConfig.setProjectId(FrameworkUtil2.getChishipDefaultProperties().getId());
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria()
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId())
                .andAppIdEqualTo(thirdApplicationKeyConfig.getAppId());
        if (thirdApplicationKeyConfigMapper.countByExample(applicationKeyConfigExample) > 0) {
            return BaseResult.error("appId已存在,请重新输入！");
        }
        return super.insertSelective(thirdApplicationKeyConfig);
    }

    @Override
    public BaseResult updateByPrimaryKeySelective(ThirdApplicationKeyConfig thirdApplicationKeyConfig) {
        thirdApplicationKeyConfig.setProjectId(FrameworkUtil2.getChishipDefaultProperties().getId());
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria()
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId())
                .andAppIdEqualTo(thirdApplicationKeyConfig.getAppId())
                .andIdNotEqualTo(thirdApplicationKeyConfig.getId());
        if (thirdApplicationKeyConfigMapper.countByExample(applicationKeyConfigExample) > 0) {
            return BaseResult.error("appId已存在,请重新输入！");
        }
        return super.updateByPrimaryKeySelective(thirdApplicationKeyConfig);
    }

    @Override
    public BaseResult initConfig(Byte type) {
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria()
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId()).andTypeEqualTo(type);
        List<ThirdApplicationKeyConfig> applicationKeyConfigs = thirdApplicationKeyConfigMapper
                .selectByExample(applicationKeyConfigExample);
        if (applicationKeyConfigs.isEmpty()) {
            return BaseResult.ok(null);
        }
        return BaseResult.ok(applicationKeyConfigs.get(0));
    }

    @Override
    public BaseResult config(ThirdApplicationKeyConfig applicationKeyConfig) {
        ThirdApplicationKeyConfigExample applicationKeyConfigExample = new ThirdApplicationKeyConfigExample();
        applicationKeyConfigExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO)
                .andProjectIdEqualTo(FrameworkUtil2.getChishipDefaultProperties().getId())
                .andTypeEqualTo(applicationKeyConfig.getType());
        List<ThirdApplicationKeyConfig> applicationKeyConfigs = thirdApplicationKeyConfigMapper
                .selectByExample(applicationKeyConfigExample);
        if (applicationKeyConfigs.isEmpty()) {
            applicationKeyConfig.setProjectId(FrameworkUtil2.getChishipDefaultProperties().getId());
            super.insertSelective(applicationKeyConfig);
            return BaseResult.ok();
        }
        applicationKeyConfig.setId(applicationKeyConfigs.get(0).getId());
        super.updateByPrimaryKeySelective(applicationKeyConfig);
        return BaseResult.ok();
    }

    @Override
    public BaseResult getPayConfig() {
        Map<String, Object> result = new HashMap<>(7);
        JSONObject wxJson = JSON.parseObject(JSON.toJSONString(new WxPayV3Config()));
        wxJson.put("notifyUrl", notifyDomain + "/wxV3/payNotify/{TRADE_TYPE}");
        wxJson.put("refundUrl", notifyDomain + "/wxV3/refundNotify");
        wxJson.put("transferUrl", notifyDomain + "/wxV3/transferNotify");
        wxJson.put("appId2", wxAppId2);
        wxJson.put("appId3", wxAppId3);
        result.put("wx", wxJson);

        JSONObject zfbJson = JSON.parseObject(JSON.toJSONString(new AliPayConfig()));
        zfbJson.put("notifyUrl", notifyDomain + "/ali/payNotify/{TRADE_TYPE}");
        result.put("zfb", zfbJson);

        JSONObject zfbMpJson = JSON.parseObject(JSON.toJSONString(chishipZfbMpProperties));
        zfbMpJson.put("notifyUrl", notifyDomain + "/ali/payNotify/{TRADE_TYPE}");
        result.put("zfbMp", zfbMpJson);
        TradeTypeEnum[] tradeTypeEnums = TradeTypeEnum.values();
        Map<String, String> tradTypeMap = new HashMap<>(tradeTypeEnums.length);
        for (TradeTypeEnum tradeTypeEnum : tradeTypeEnums) {
            tradTypeMap.put(tradeTypeEnum.getCode(), tradeTypeEnum.getMessage());
        }
        result.put("tradeType", tradTypeMap);
        return BaseResult.ok(result);
    }

}
